#include "widget.h"
#include "ui_widget.h"

extern "C"
{
    #include <fcntl.h>
    #include <sys/stat.h>
    #include <unistd.h>
    #include <sys/types.h>
}

#include <QTimer>
#include <QDebug>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    ledfd = open("/dev/led_drv", O_RDWR);
    if(ledfd == -1)
    {
        perror("open failed");
        return;
    }

    curled = 0;

    ledtimer = new QTimer(this);
    ledtimer->setInterval(1000);

    connect(ledtimer, SIGNAL(timeout()), this, SLOT(lednext()));
}

Widget::~Widget()
{
    ::close(ledfd);
    delete ui;
}




void Widget::on_pushButton_open_clicked()
{
    qDebug() << "openbtn";
    ledtimer->start();
}

void Widget::lednext()
{
    qDebug() << "lednext()";

    char ledbuf[2] = {0};
    ledbuf[1] = ledlist[curled];

    int ret;

    ret = write(ledfd, ledbuf, 2);
    if(ret != 2)
    {
        qDebug() << "write faied";
        return;
    }

    curled = (curled + 1) % 4;

    ledbuf[1] = ledlist[curled];
    ledbuf[0] = 1;

    ret = write(ledfd, ledbuf, 2);
    if(ret != 2)
        qDebug() << "write faied";
}


void Widget::on_pushButton_close_clicked()
{
    qDebug() << "closebtn()";
    ledtimer->stop();
}

